/*
 * ConnectionPanel.java
 *
 * Created on 6 novembre 2007, 19:59
 */

package jtalk.view;

import java.beans.PropertyChangeEvent;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import jtalk.controller.DefaultController;
import jtalk.controller.Properties;
import jtalk.logging.Logger;

/**
 *
 * @author  remy
 */
public class ConnectionPanel extends AbstractViewPanel {
    
	private static final long serialVersionUID = 3026519607367354093L;
	/** Creates new form ConnectionPanel */
    public ConnectionPanel(DefaultController controller) {
    	this.controller = controller;
        initComponents();
        init();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        loginTextField = new javax.swing.JTextField();
        serverTextField = new javax.swing.JTextField();
        connectButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        saveCheckBox = new javax.swing.JCheckBox();
        jProgressBar = new javax.swing.JProgressBar();
        passwordField = new javax.swing.JPasswordField();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Connection parameters"));
        jLabel1.setText("Server");

        jLabel2.setText("Login");

        jLabel3.setText("Password");

        connectButton.setText("connect");
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        jLabel4.setText("save paramaters");

        saveCheckBox.setSelected(true);
        saveCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        saveCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
        saveCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveCheckBoxActionPerformed(evt);
            }
        });

        jProgressBar.setIndeterminate(true);

        passwordField.setText("jPasswordField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(12, 12, 12)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(passwordField, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                                    .addComponent(loginTextField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(serverTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE))
                                .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(saveCheckBox))))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jProgressBar, 0, 0, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addComponent(connectButton)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(serverTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(saveCheckBox))
                .addGap(14, 14, 14)
                .addComponent(connectButton)
                .addGap(23, 23, 23)
                .addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(35, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void saveCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveCheckBoxActionPerformed
        if(!saveCheckBox.isSelected()) {
        	    
        	Logger.getLogger(this).debug("Cleaning configuration");
        	
	    	try {
	    		
	    		connectionParameters.setProperty("server", "server");
	    		connectionParameters.setProperty("login", "username");
	    		connectionParameters.setProperty("pass", "password");
	    		
				connectionParameters.save();
				
			} catch (ConfigurationException e) {
				Logger.getLogger(this).error("Error while cleaning configuration ...");
				e.printStackTrace();
			}	    	
        }
    }//GEN-LAST:event_saveCheckBoxActionPerformed

    private void init() {
    	
    	jProgressBar.setVisible(false);
    	
    	try {
    		
			connectionParameters = new PropertiesConfiguration(".config/connection.properties");			
			connectionParameters.setLogger(Logger.getLogger(connectionParameters.getClass()));
												
			serverTextField.setText(connectionParameters.getString("server"));
	    	loginTextField.setText(connectionParameters.getString("login"));
	    	passwordField.setText(connectionParameters.getString("pass"));	    	
			
		} catch (ConfigurationException e) {
			Logger.getLogger(this).error("Cannot create configuration file : " + e.getMessage());
			e.printStackTrace();
		}
    	    	    	
    }
    
    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
    	
    	connectButton.setEnabled(false);
    	
    	jProgressBar.setVisible(true);
    	    	    
    	Thread task = new Thread() {
			public void run() {				
				controller.changeServer(serverTextField.getText());  
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {}
				
		        controller.login(loginTextField.getText(), new String(passwordField.getPassword()));
		        jProgressBar.setVisible(false);
		        connectButton.setEnabled(true);		        
			}    		
    	};
    	
    	task.start();
                        
    }//GEN-LAST:event_connectButtonActionPerformed

    public void modelPropertyChange(PropertyChangeEvent evt) {
    	
    	//Connection Events
    	if(evt.getPropertyName().equals(Properties.AUTHENTICATED.toString())) {
            if((Boolean)evt.getNewValue()) {        
            	            	            	
            	if(saveCheckBox.isSelected()) {
            		try {
                		Logger.getLogger(this).debug("Saving connection paramaters");
                    	connectionParameters.setProperty("server", serverTextField.getText());
                    	connectionParameters.setProperty("login", loginTextField.getText());
                    	connectionParameters.setProperty("pass", new String(passwordField.getPassword()));
    					connectionParameters.save();
    				} catch (ConfigurationException e) {
    					Logger.getLogger(this).error("Cannot save configuration : " + e.getMessage());
    					e.printStackTrace();
    				}
            	}            	            	
            }
        }
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton connectButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JProgressBar jProgressBar;
    private javax.swing.JTextField loginTextField;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JCheckBox saveCheckBox;
    private javax.swing.JTextField serverTextField;
    // End of variables declaration//GEN-END:variables
    
    //Other variables
    private DefaultController controller;
    private PropertiesConfiguration connectionParameters;
    //End
}
